package com.atguigu.gmall.service.impl;


import com.atguigu.gmall.entity.PlatformPropertyValue;
import com.atguigu.gmall.entity.SkuPlatformPropertyValue;
import com.atguigu.gmall.mapper.PlatformPropertyKeyMapper;
import com.atguigu.gmall.service.PlatformPropertyKeyService;
import com.atguigu.gmall.entity.PlatformPropertyKey;
import com.atguigu.gmall.service.PlatformPropertyValueService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Transactional
@Service
public class PlatformPropertyKeyServiceImpl extends ServiceImpl<PlatformPropertyKeyMapper, PlatformPropertyKey> implements PlatformPropertyKeyService {

    @Autowired
    private PlatformPropertyValueService propertyValueService;

    @Override
    public List<PlatformPropertyKey> getPlatformPropertyByCategoryId(Long category1Id, Long category2Id, Long category3Id) {
        return baseMapper.selectPlatformPropertyByCategoryId(category1Id,category2Id,category3Id);
    }
    @Override
    public void savePlatformProperty(PlatformPropertyKey platformPropertyKey) {
        //获取平台属性值
        List<PlatformPropertyValue> propertyValueList = platformPropertyKey.getPropertyValueList();
        //获取key的id,如果是空的，执行新增，不是空值，执行修改
        if (StringUtils.isEmpty(platformPropertyKey.getId()))
            baseMapper.insert(platformPropertyKey);  //需要主键回填
        baseMapper.updateById(platformPropertyKey);
        if (!StringUtils.isEmpty(propertyValueList)){
            //如果内容不为空
            for (PlatformPropertyValue ppv : propertyValueList) {
                ppv.setPropertyKeyId(platformPropertyKey.getId()); //回填key的id为property_key_id
            }
            propertyValueService.saveBatch(propertyValueList);//执行批量新增
        }
    }

    @Override
    public List<PlatformPropertyKey> getPlatformProperty(List<SkuPlatformPropertyValue> values) {
        List<PlatformPropertyKey> platformPropertyKeys = new ArrayList<>();
        values.stream().forEach(item -> {
            PlatformPropertyKey platformPropertyKey = baseMapper.selectById(item.getPropertyKeyId());
            QueryWrapper<PlatformPropertyValue> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("property_key_id", item.getPropertyKeyId());
            List<PlatformPropertyValue> list = propertyValueService.list(queryWrapper);
            platformPropertyKey.setPropertyValueList(list);
            platformPropertyKeys.add(platformPropertyKey);
        });
        return platformPropertyKeys;
    }
}
